package com.vvv.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.vvv.constants.RabbitMQConstant;
import com.vvv.model.dto.UserCourseMessage;
import com.vvv.model.entity.CourseInfo;
import com.vvv.model.entity.UserCourseinfo;
import com.vvv.service.CourseInfoService;
import com.vvv.service.UserCourseinfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author vvv
 * @date 2023-12-08 16 09
 * discription
 */
@Component
@Slf4j
public class GrabbingCourseConsumer {


    @Resource
    private UserCourseinfoService userCourseinfoService;

    @Resource
    private CourseInfoService courseInfoService;

    @Transactional
    @RabbitListener(queues = {RabbitMQConstant.GRABBING_QUEUE_NAME})
    public void consume(UserCourseMessage userCourseMessage) {
        Long courseId = userCourseMessage.getCourseId();
        // save
        UserCourseinfo userCourseinfo = new UserCourseinfo();
        BeanUtils.copyProperties(userCourseMessage, userCourseinfo);
        userCourseinfoService.save(userCourseinfo);

        // deduction
        LambdaUpdateWrapper<CourseInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CourseInfo::getId, courseId);
        updateWrapper.setSql("leftNum = leftNum - 1");
        boolean isSuccess = courseInfoService.update(updateWrapper);

        if (!isSuccess) {
            throw new RuntimeException("message: " + userCourseMessage + " consumer error");
        }
        log.info("message: " + userCourseMessage + " consumer succeed");
    }
}
